﻿using Newtonsoft.Json;
using PublicCom;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace UpdateApp
{
    public partial class Default : System.Web.UI.Page
    {
        protected string display = "";
        protected string date = "";
        protected int flag = 1;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Random rd = new Random();

                flag = rd.Next(1, 8);

                List<string> list = new List<string> { "WinCE", "WinXP" };

                list.ForEach(i =>
                {
                    if (Request.Browser.Platform.Equals(i, StringComparison.CurrentCultureIgnoreCase))
                        Response.Redirect("Simple.aspx");
                });

                string name = Request["key"];

                if (!string.IsNullOrEmpty(name))
                {
                    string version = ConfigurationManager.AppSettings[name];

                    string path = ConfigurationManager.AppSettings[name + "Path"];

                    if (string.IsNullOrEmpty(version))
                        version = "1.0.0.0";

                    Response.ContentEncoding = Encoding.UTF8;

                    Response.Write(version + ">" + path);

                    Response.End();
                }

                if (!string.IsNullOrEmpty(Request["isSave"]))
                {
                    Common.ChangeConfig(Request["isSave"]);
                }

                if (!Common.CheckUserHost())
                    display = "none";

                Session.Remove("FileList");

                //删除超出保存期限的文件夹
                Thread thread = new Thread(FileHelper.DelDirectories);
                thread.Start();
            }
            else
            {
                UploaderFileByBaidu up = new UploaderFileByBaidu();

                up.SaveFile();
            }

            date = DateTime.Now.ToString("yyyy-MM-dd");
        }

        protected void btnZip_ServerClick(object sender, EventArgs e)
        {
            List<string> fileList = Session["FileList"] as List<string> ?? Session["ZipFile"] as List<string> ?? new List<string>();

            string script = "";

            //文件数量为0时 
            if (fileList.Count == 0)
            {
                Regex ipReg = new Regex(@"\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3}");

                //删除已上传的更新版本
                if (this.password.Value.IndexOf("/") > 0)
                {
                    string path = FileHelper.GetDownloadPath(this.password.Value);

                    Directory.Delete(path, true);

                    Common.ChangeAppConfig(this.password.Value, "", true);
                }
                //将输入框的内容加入翻译常量
                else if (this.password.Value.IndexOf('=') > 0)
                {
                    var json = FileHelper.GetAppData("Translate");

                    var dic = json != null ? JsonConvert.DeserializeObject<Dictionary<string, string>>(json) : new Dictionary<string, string>();

                    var arr = this.password.Value.Trim().Split('=');

                    if (dic.ContainsKey(arr[0]))
                        dic.Remove(arr[0]);

                    dic.Add(arr[0], arr[1] + (arr.Length > 2 ? "=" + arr[2] : ""));

                    FileHelper.SetAppData("Translate", JsonConvert.SerializeObject(dic));
                }
                //将当前ip加入白名单
                else if (ipReg.IsMatch(this.password.Value))
                    Common.ChangeIpConfig(this.password.Value);
                //将密码框的值更新到web.config的isSave中， 用于开启调试（isSave=1时 不验证IP白名单）
                else if (!string.IsNullOrEmpty(this.password.Value))
                    Common.ChangeConfig(this.password.Value.Trim());
                //跳转在线文档
                else
                    Response.Redirect("Template.aspx");

                this.password.Value = string.Empty;
            }
            else
            {
                //更新程序的格式：名称/版本号
                //重新输入名称/版本号并点击设置可以删除当前版本
                if (this.password.Value.IndexOf("/") > 0)
                {
                    string path = FileHelper.GetDownloadPath(this.password.Value);

                    string name = Path.GetFileName(fileList[0]);

                    File.Copy(fileList[0], Path.Combine(path, name), true);

                    Common.ChangeAppConfig(this.password.Value, name);

                    Session.Remove("ZipFile");
                    this.password.Value = string.Empty;
                }
                //移入临时空间
                else if (this.password.Value == "11")
                {
                    foreach (var item in fileList)
                    {
                        string tempPath = Path.Combine(FileHelper.GetTempPath(), Path.GetFileName(item));
                        if (File.Exists(tempPath))
                            File.Delete(tempPath);

                        if (File.Exists(item))
                            File.Move(item, tempPath);
                    }
                }
                else
                {
                    string file = fileList[fileList.Count - 1];

                    //跳转到接口生成页面
                    if (file.EndsWith(".cs", StringComparison.CurrentCultureIgnoreCase))
                    {
                        //直接使用window.open('Template.aspx')打开新窗口会被浏览器拦截                        
                        Response.Redirect("ShowDoc.aspx");
                    }
                    //创建压缩包
                    else if (!file.EndsWith(".zip", StringComparison.CurrentCultureIgnoreCase))
                    {
                        string fileZip = FileHelper.CreateZipFile(fileList, this.password.Value);

                        if (fileZip != "")
                        {
                            fileList.Clear();
                            fileList.Add(fileZip);

                            Session["ZipFile"] = fileList;
                        }
                    }
                    //解压压缩包
                    else
                    {
                        //密码为空时解压上传的zip文件，并打开文件所在目录，用于发布测试页面
                        string dir = Path.Combine(FileHelper.GetUploadPath(), DateTime.Now.ToString("yyyy-MM-dd"), Path.GetFileNameWithoutExtension(file));

                        ZipHelper.UnZip(file, dir, null);

                        //查询html所在的目录
                        string dirName = FileHelper.GetFileDir(dir);

                        //直接打开目录
                        //dir = dirName.Replace(Path.GetDirectoryName(FileHelper.GetUploadPath()), "");
                        // \\Upload\\2021-08-06\\web\\web\\
                        //Response.Redirect(dir);

                        dir = dirName.Replace(FileHelper.GetUploadPath() + "\\", "");
                        // 2021-08-06\\web\\web\\

                        dir = HttpUtility.UrlEncode(dir);
                        Response.Redirect("Files.aspx?date=" + dir);
                    }
                }
            }

            //解决点击按钮后，刷新页面会触发按钮事件的问题
            script = script != "" ? script : "<script>window.location.href='Default.aspx'; </script>";

            Response.Write(script);
        }
    }
}